package com.sk.sourcecircle.activity.community;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.jude.rollviewpager.hintview.IconHintView;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.community.fragment.AlbumFragment;
import com.sk.sourcecircle.activity.community.fragment.ChatFragment;
import com.sk.sourcecircle.activity.community.fragment.SourceFragment;
import com.sk.sourcecircle.activity.home.activity.AddFriendActivity;
import com.sk.sourcecircle.activity.home.activity.RoundGroupActivity;
import com.sk.sourcecircle.activity.home.activity.SearchToAddActivity;
import com.sk.sourcecircle.adapter.BannerAdapter;
import com.sk.sourcecircle.adapter.MyPagerAdapter;
import com.sk.sourcecircle.adapter.SpinnerAdapter;
import com.sk.sourcecircle.base.BaseFragment;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.common.Constants;
import com.sk.sourcecircle.dialog.ShareDialogFragment;
import com.sk.sourcecircle.entity.GroupListBean;
import com.sk.sourcecircle.entity.HomeBannerBean;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SnackUtils;
import com.sk.sourcecircle.utils.UIUtils;
import com.sk.sourcecircle.view.FixedProportionViewPager;
import com.sk.sourcecircle.view.NoticeView;
import com.sk.sourcecircle.zxing.activity.CaptureActivity;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by sk on 2017/11/19.
 */

@RuntimePermissions
public class CommunityFragment extends BaseFragment implements View.OnClickListener, HandleDataCallBack, IUiListener {
    @BindView(R.id.menu)
    ImageView menu;
    @BindView(R.id.search)
    ImageView search;
    @BindView(R.id.group_spinner)
    Spinner groupSpinner;
    @BindView(R.id.my_table)
    TabLayout myTable;
    @BindView(R.id.my_pager)
    ViewPager myPager;
    Unbinder unbinder;

    ChatFragment chatFragment;
    SourceFragment sourceFragment;
    AlbumFragment albumFragment;
    @BindView(R.id.banner_pg)
    FixedProportionViewPager bannerPg;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    Unbinder unbinder1;
    @BindView(R.id.notice_view)
    NoticeView noticeView;
    Unbinder unbinder2;
    private List<Fragment> fragmentList = new ArrayList<>();

    private boolean isopen = false;
    PopupWindow popupWindow;

    private String groupId = "";
    private LoadingDialog loadingDialog;


    @Override
    protected int getContentView() {
        return R.layout.fragment_community;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        noticeView.getNotice("-1");

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        initFragments();
        bannerPg.setHintView(new IconHintView(mContext, R.drawable.point_focus, R.drawable.point_normal, UIUtils.dip2px(mContext, 16)));
    }

    @OnClick({R.id.menu, R.id.search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.menu:
                if (!isopen) {
                    showPopWindow();
                } else {
                    isopen = false;
                    popupWindow.dismiss();
                }
                break;
            case R.id.search:
                Intent intent = new Intent(mContext, SearchToAddActivity.class);
                startActivity(intent);
                break;
        }
    }


    private void initFragments() {
        chatFragment = new ChatFragment();
        sourceFragment = new SourceFragment();
        albumFragment = new AlbumFragment();

        fragmentList.add(chatFragment);
        fragmentList.add(albumFragment);
        fragmentList.add(sourceFragment);

        myPager.setOffscreenPageLimit(3);
        MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager(), getResources().getStringArray(R.array.community_array), fragmentList);
        myPager.setAdapter(adapter);
        myTable.setupWithViewPager(myPager);
    }

    private void showPopWindow() {
        RelativeLayout relativeLayout = new RelativeLayout(mContext);
        View view = LayoutInflater.from(mContext).inflate(R.layout.home_pop, relativeLayout, false);
        TextView addFriend = view.findViewById(R.id.add_friend);
        TextView roundGroup = view.findViewById(R.id.round_group);
        TextView share = view.findViewById(R.id.share);
        TextView scan = view.findViewById(R.id.scan);
        addFriend.setOnClickListener(this);
        roundGroup.setOnClickListener(this);
        share.setOnClickListener(this);
        scan.setOnClickListener(this);
        relativeLayout.addView(view);
        popupWindow = new PopupWindow(relativeLayout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setClippingEnabled(false);

        ColorDrawable dw = new ColorDrawable(0);
        popupWindow.setBackgroundDrawable(dw);

        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        relativeLayout.measure(w, h);
        int width = relativeLayout.getMeasuredWidth();
        popupWindow.showAsDropDown(menu, -width + menu.getMeasuredWidth(), 0);
        isopen = true;

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_friend:
                Intent addIntent = new Intent(mContext, AddFriendActivity.class);
                startActivity(addIntent);
                popupWindow.dismiss();
                isopen = false;
                break;
            case R.id.round_group:
                Intent groupIntent = new Intent(mContext, RoundGroupActivity.class);
                startActivity(groupIntent);
                popupWindow.dismiss();
                isopen = false;

                break;
            case R.id.share:
                ShareDialogFragment shareDialogFragment = new ShareDialogFragment();
                shareDialogFragment.setTargetUrl(Constants.App_url);
                shareDialogFragment.setImageUrl("");
                shareDialogFragment.setQqListener(this);
                shareDialogFragment.setTitle("源圈");
                shareDialogFragment.setSummary("源圈社区”是北京源圈传媒科技有限公司自主开发运营的一款APP应用，是消费升级领域首家本地化精准数据匹配平台。以本地化社群APP为载体，用户运营为中心，串连社区、中小微企业、校园三大场景，运用“去中心化”的平台方式，让各实体社群实现精准用户运营、精准需求匹配、精准营销推广。立志成为一个让人人都能实现价值的平台、一个基于实体场景的精准大数据平台。");
                shareDialogFragment.show(getActivity().getFragmentManager(), "share");
                popupWindow.dismiss();
                isopen = false;

                break;
            case R.id.scan:
                popupWindow.dismiss();
                isopen = false;
                CommunityFragmentPermissionsDispatcher.startScanWithPermissionCheck(this);
                break;
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        switch (tag) {
            case 0:
                final GroupListBean groupListBean = JSON.parseObject(result, GroupListBean.class);
                final List<GroupListBean.DataBean> dataBeanList = groupListBean.getData();

                final StringBuilder sb = new StringBuilder();

                for (int i = 0; i < dataBeanList.size(); i++) {
                    if (i == dataBeanList.size() - 1) {
                        sb.append(dataBeanList.get(i).getCommunity_id());
                    } else {
                        sb.append(dataBeanList.get(i).getCommunity_id()).append(",");
                    }
                }

                GroupListBean.DataBean dataBean = new GroupListBean.DataBean();
                dataBean.setCommunity_name("全部");
                dataBeanList.add(0, dataBean);
                SpinnerAdapter adapter = new SpinnerAdapter(dataBeanList, mContext);
                groupSpinner.setAdapter(adapter);
                groupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                        if (position == 0) {
                            groupId = sb.toString();

                        } else {
                            groupId = String.valueOf(dataBeanList.get(position).getCommunity_id());
                        }
                        sourceFragment.doRefresh(groupId);
                        albumFragment.doRefresh(groupId);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
                break;
            case 1:
                loadingDialog.cancelDialog();
                HomeBannerBean homeBannerBean = JSON.parseObject(result, HomeBannerBean.class);
                List<HomeBannerBean.DataBean> bannerList = homeBannerBean.getData();
                initBanner(bannerList);
                break;
        }

    }


    private void initBanner(List<HomeBannerBean.DataBean> bannerList) {
        BannerAdapter adapter = new BannerAdapter(bannerList, mContext);
        bannerPg.setAdapter(adapter);
    }


    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }


    public void refresh() {
        AppApi.getJoinedGroup(this, 0, getActivity());
        AppApi.getGroupBanner(this, 1, getActivity());
    }

    @Override
    public void onComplete(Object o) {

    }

    @Override
    public void onError(UiError uiError) {

    }

    @Override
    public void onCancel() {

    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startScan() {
        Intent scanIntent = new Intent(mContext, CaptureActivity.class);
        startActivityForResult(scanIntent, 1);

    }

    // 向用户说明为什么需要这些权限（可选）
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(mContext)
                .setMessage("扫一扫需要使用您的相机！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 用户拒绝授权回调（可选）
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForCamera() {
        SnackUtils.showError(mRootView, "您拒绝了相机权限！");
    }

    // 用户勾选了“不再提醒”时调用（可选）
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForCamera() {
        new AlertDialog.Builder(mContext)
                .setMessage("您已禁止相机权限,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }


    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        CommunityFragmentPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
